<template>
  <PageWrapDrawer
:show="show" :isUpdate="props.isUpdate" :title="title" title-suffix="货物"
  ref="containerRef"
  @success="onSubmit"
  @on-drawer-close="onClose">
    <Form
    name="basic"
    :model="insideData.data"
    :label-col="{ span: 6 }"
    :wrapper-col="{ span: 16 }"
    size="middle"
    autocomplete="off"
    layout="horizontal"
    >
    <Card hoverable :bordered="false" size="small">
      <template #title><h3 class="card-title">| 货物基础信息</h3></template>
        <Row>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="货物编码" name="code" v-bind="validateInfos['data.code']">
              <a-input v-model:value="insideData.data.code" :maxlength="8">
                <template #addonAfter>
                  <Tooltip title="生成编号">
                    <a @click="insideData.data.code = genCode()">
                      <a><CodeOutlined /></a>
                      <!-- 生成 -->
                    </a>
                  </Tooltip>
                </template>
              </a-input>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="分类" name="parentId" v-bind="validateInfos['data.cateId']">
              <TreeSelect
              v-model:value="insideData.data.cateId" placeholder="请选择"
                style="width: 100%"
                allow-clear
                tree-default-expand-all
                :fieldNames="{value: 'ID', label: 'name', children: 'children'}"
                :tree-data="treeDataOfCate"
                :get-popup-container="(tn) => tn.parentNode"
              />
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="货物名称" name="name" v-bind="validateInfos['data.name']">
              <a-input v-model:value="insideData.data.name"/>
            </FormItem>
          </Col>
          <!-- <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="价格" name="price">
              <InputNumber v-model:value="insideData.data.price" :min="0"
              style="width: 100%;"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => value.replace(/\$\s?|(,*)/g, '')"
              />
            </FormItem>
          </Col> -->
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="货物单位" name="unit">
              <a-input v-model:value="insideData.data.unit"/>
            </FormItem>
          </Col>
          <!-- <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="规格" name="specs">
              <a-input v-model:value="insideData.data.specs" placeholder=""/>
            </FormItem>
          </Col> -->
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="默认重量" name="weight">
              <InputNumber v-model:value="insideData.data.weight" :step="10" allowClear style="width: 100%;">
                <template #addonAfter>KG</template>
              </InputNumber>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="尺寸/体积" name="volume">
              <InputNumber v-model:value="insideData.data.volume" allowClear style="width: 100%;"/>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="默认价格" name="price">
              <InputNumber v-model:value="insideData.data.price" prefix="￥" :step="10" allowClear style="width: 100%;"/>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="货物条形码" name="barcode">
              <a-input v-model:value="insideData.data.barcode" allowClear>
                <template #suffix><BarcodeOutlined /></template>
              </a-input>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="有效期" name="validDate">
              <vxe-input 
              v-model="insideData.data.validDate"
              style="width: 100%;"
              placeholder="请选择" type="datetime" transfer/>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="安全库存" name="minStock">
              <InputNumber v-model:value="insideData.data.minStock" :min="0" :step="10" style="width:100%;"/>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="启用" name="enasble">
              <RadioGroup v-model:value="insideData.data.enable">
                <Radio :value="1">启用</Radio>
                <Radio :value="2">禁用</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
            <FormItem label="赠品" name="isGift">
              <RadioGroup v-model:value="insideData.data.isGift">
                <Radio :value="1">是</Radio>
                <Radio :value="2">不是</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem
            label="备注" name="memo" 
            :label-col="{ xs: {span: 6}, sm: {span: 6}, md: {span: 6}, lg: {span: 6}, xl: {span: 3}, xxl: {span: 3} }"
            :wrapper-col="{ xs: {span: 16}, sm: {span: 16}, md: {span: 16}, lg: {span: 16}, xl: {span: 20}, xxl: {span: 20} }"
            >
              <a-textarea
              v-model:value="insideData.data.memo" :autoSize="{ minRows: 2, maxRows: 6, }"
              placeholder="货物备注..."/>
            </FormItem>
          </Col>
        </Row>
      </Card>

    <!-- '提示：支持 .png .gif .jpg .jpeg 类型的图片，建议单张图片大小不超过2M。',
    `最多上传${maxCountImage}张，且第一张是商品主图`, -->
    <Card hoverable :bordered="false" size="small" v-if="false">
      <template #title><h3 class="card-title">| 货物图片</h3></template>
      <Upload
        :action="upImageUrl"
        :headers="header"
        :maxCount="maxCountImage"
        accept=".png,.gif,.jpg,.jpeg"
        list-type="picture-card"
        v-model:file-list="fileList"
        @preview="handlePreview"
        @change="handleUploadChange"
        >
        <div v-if="fileList.length < maxCountImage">
          <a-button><UploadOutlined/>上传</a-button>
        </div>
      </Upload>
      <Modal :visible="previewVisible" :footer="null" width="70%" centered @cancel="previewVisible = false">
        <img alt="" style="width: 100%;padding:0 12%;" :src="previewImage" />
        </Modal>
    </Card>
    </Form>
  </PageWrapDrawer>
</template>
<script lang="ts" name="InfoOfGoods" setup>
import { BarcodeOutlined, CodeOutlined, UploadOutlined } from '@ant-design/icons-vue';
import type { TreeSelectProps } from 'ant-design-vue';
import {
Card, Col,
Form, FormItem, InputNumber, Modal, Radio, RadioGroup, Row,
Tooltip, TreeSelect, Upload
} from 'ant-design-vue';
import { onMounted, reactive, ref, toRaw, watch, watchPostEffect, } from 'vue';
import { deep, } from './data';
import { create, update } from '/@/api/wms/goods';
import { getListData } from '/@/api/wms/goods-cate';
import { PageWrapDrawer } from '/@/components/PageWrapDrawer';
import { getToken } from '/@/utils/auth';
import { genCode } from "/@/utils/my";
const emit = defineEmits(['on-success', 'on-drawer-close'])
const props = defineProps({
    show: {type: Boolean, default: null,},
    isUpdate: Boolean,
    isCopy: Boolean,
    row: {type: [Object, null] as PropType<Object | null>, default: null,},
})

const containerRef = ref()

const useForm = Form.useForm;

const insideData = reactive({
  data: {
    ID: null,
    code: '',
    name: '',
    cateId: null,
    unit: null,
    specs: '',
    isGift: 2,
    enable: 1,
    memo: '',
    weight: null,
    volume: null,
    validDate: null,
    minStock: 0,
    licence: '',
    barcode: '',
    price: 0,
  }
});

const rulesRef = reactive({
  'data.code': [
    {required: true, message: '编号不能为空',},
  ],
  'data.name': [
    {required: true, message: '名称不能为空',},
  ] as unknown,
  'data.cateId': [
    {required: true, message: '分类不能为空',},
  ],
});

const title = ref('')
watchPostEffect(() => {
  let v1 = props.row as any
  if (props.show && props.isUpdate && v1) {
    let images = v1?.images
    if (images) {
      let pre = import.meta.env.VITE_GLOB_STATIC_URL
      fileList.value = images.map(e => {
        return {
          ID: e.ID,
          name: e.name,
          path: e.path,
          ext: e.ext,
          url: pre + e.path,
        }
      })
    }
  }
  if (props.show && props.isCopy) {
    title.value = '复制并创建 货物'
  }
})

const isGiftRef = ref(false)
watch(() => insideData.data.isGift, (v1, _) => {
  isGiftRef.value = (v1 !== 2)
  if (v1 !== 2) {
    insideData.data.price = 0
  }
})

const treeDataOfCate = ref<TreeSelectProps['treeData']>([])
watch(()=>props.show, (v1, _) => {
  if (v1) {
    getListData().then(dd => {
      treeDataOfCate.value = deep(dd)
    })
  }
  
})

watch(()=>props.row, (v1, _) => {
  if (v1) {
    insideData.data = {...v1} as any
  }
})

// 图片 start
const maxCountImage = ref(3)
const upImageUrl = ref('')
const header = reactive({
  "Authorization": 'Bearer '+getToken()
})
onMounted(() => {
  let url = import.meta.env.VITE_GLOB_UPLOAD_URL
  upImageUrl.value = url
})

const previewVisible = ref<boolean>(false);
const previewImage = ref('')
const fileList = ref([
  // { url: 'https://cdn.jsdelivr.net/npm/@vant/assets/leaf.jpeg' },
]);
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const handlePreview = async (file: FileItem) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
};

const handleUploadChange = ({file, fileList, event}) => {}

// 图片 end

const {resetFields, validate, validateInfos} = useForm(insideData, rulesRef, {
  onValidate: (...args) => {
  },
});

const onSubmit = () => {
  validate()
    .then(async () => {
      let images = fileList.value.map((e:any) => {
        return {
          name: e?.response?.result?.name || e?.name,
          path: e?.response?.result?.path || e?.path,
          ext: e?.response?.result?.ext || e?.ext,
        }
      }) || []
      let params = { goods: toRaw(insideData.data), images: images }
      if (props.isUpdate) {
        await update(params).then(() => {
          onClose()
        })
      } else {
        await create(params).then(() => {
          onClose()
        })
      }
      emit('on-success')
    })
}

const onClose = () => {
  Object.assign(insideData, {data: {}})
  title.value = ''
  fileList.value = []
  resetFields();
  emit('on-drawer-close');
};

</script>
<style scoped>
.card-title{
  /* opacity: .75; */
  color: #f90;
}
:deep().ant-card:not(:last-child){
  margin-bottom: 12px;
}
</style>
